package quark

import (
	log2 "answer5/log"
	"answer5/unti"
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var(
	isStart *bool
	quarkQuestion unti.Question
	quarkRequest *http.Request
	quarkApps=map[string]string{"kuaiShou":"ttkx"}
	err error
	httpClient   = &http.Client{Timeout: time.Duration(3 * time.Second)}
	regCorrect   = regexp.MustCompile(`"correct":(\d)`)
	IsTest = false
)

func Start(start *bool,app *string){
	go log2.LogPrint("开始夸克"+*app)
	isStart = start

	quarkRequest, err = http.NewRequest("GET", "https://answer-quark.sm.cn/answer/curr?format=json&activity="+quarkApps[*app], nil)
	if IsTest{
		quarkRequest, err = http.NewRequest("GET", "http://127.0.0.1:8818/scripts/quarkTest.json", nil)
	}
	quarkRequest.Header.Set("User-Agent", "Mozilla/5.0 (Linux; U; Android 9; zh-Hans-CN; MI 5 Build/PKQ1.190806.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 Quark/3.8.1.125 Mobile Safari/537.36")
	//quarkRequest.Header.Set("Referer", "https://answer-quark.sm.cn/answer/?uc_param_str=dnntnwvepffrgibijbprsvdsdicheiniut&source=h5navi_add")
	//quarkRequest.Header.Set("Cookie", "__wpkreporterwid_=c45c4d66-cc83-4a45-b0a7-0447e2ec37cc; sm_uuid=be439a5785fbf10552e2f20ca4af38f8%7C41477020131%7C%7C1576673007; sm_diu=9fcb1285bb5939136ccfb34b47c075be%7C41477020131%7C1351f3ec4ee90dfab4%7C1576673001; sm_sid=909e2e943449d8f11b03f6466340a88e; sec=5e0f306539866a319402975e64398b448523ddb2")
	if err != nil {
		log.Println("quark:",err)
		go log2.ErrorPrint(err.Error())
	}

	go getQuestion()
}
func Stop(start *bool){
	isStart = start
}

func getQuestion(){
	for{
		time.Sleep(1000*time.Millisecond)

		if !*isStart{
			break
		}

		resp, err := httpClient.Do(quarkRequest)
		if err != nil {
			log.Println("quarkRequest 异常1")
			go log2.ErrorPrint(err.Error())
			continue
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Println("quarkRequest 异常2")
			go log2.ErrorPrint(err.Error())
			continue
		}

		responseData := &QuarkQuestionResponse{}
		if err = json.Unmarshal(body, responseData); err != nil {
			body = bytes.Replace(body, []byte(`"round":""`), []byte(`"round":0`), -1)
			if err = json.Unmarshal(body, responseData); err != nil {
				body = regCorrect.ReplaceAll(body, []byte(`"correct":"$1"`))
				if err = json.Unmarshal(body, responseData); err != nil {
					log.Println("quarkRequest 异常3")
					go log2.ErrorPrint(err.Error())
					//fmt.Println(string(body))
					continue
				}
			}
		}


		//responseData = &testQuarkQuestion

		if responseData.Data.Round > 0 {
			resultIndex, _ := strconv.Atoi(responseData.Data.Correct)
			//fmt.Println(responseData.Data.Round, quarkQuestion.Round)
			if responseData.Data.Round > quarkQuestion.Round {
				quarkQuestion.Title = responseData.Data.Title
				quarkQuestion.Round = responseData.Data.Round
				//fmt.Println(1, resultIndex)
				if resultIndex >= 0 {
					quarkQuestion.Result = strings.Replace(responseData.Data.Options[resultIndex].Title, "|-|", "或", -1)
				} else {
					quarkQuestion.Result = ""
				}
				//fmt.Println(2, resultIndex)
				//quarkQuestion.App = "quark"
				if strings.Index(responseData.Data.Options[0].Title, "|-|") > -1 {
					optionMap := make(map[string]bool)
					for _, option := range responseData.Data.Options {
						os := strings.Split(option.Title, "|-|")
						for _, o := range os {
							optionMap[o] = true
						}
					}
					options := make([]unti.Option, 0)
					for o := range optionMap {
						options = append(options, unti.Option{Text: strings.Trim(o, "")})
					}
					quarkQuestion.Options = options
				} else {
					options := make([]unti.Option, len(responseData.Data.Options))
					for i, option := range responseData.Data.Options {
						options[i] = unti.Option{Text: strings.Trim(option.Title, "")}
					}
					quarkQuestion.Options = options
				}
				go unti.NewQuestion(&quarkQuestion)
			} else if quarkQuestion.Result == "" && resultIndex >= 0 {
				quarkQuestion.Result = strings.Replace(responseData.Data.Options[resultIndex].Title, "|-|", "或", -1)
				go unti.NewAnswer(&quarkQuestion)
			}
		}
	}
}

func TestQuark(s *bool ,app *string){
	IsTest=true
	Start(s,app)
}

// QuarkQuestionResponse 夸克回应原始数据
type QuarkQuestionResponse struct {
	Status int           `json:"status"`
	Data   QuarkQuestion `json:"data"`
}

// QuarkQuestion 夸克回应数据
type QuarkQuestion struct {
	Round   int32           `json:"round"`
	Options []QuarkOption `json:"options"`
	Title   string        `json:"title"`
	Correct string        `json:"correct"`
}

// QuarkOption 夸克选项
type QuarkOption struct {
	Title string `json:"title"`
	Score string `json:"score"`
}